<template>
  <div class="management-container">
    <header class="header-section">
      <h2 class="title">预约管理</h2>
      <div class="stats-badge">
        <el-tag type="warning">待确认预约: {{ unconfirmedCount }}</el-tag>
      </div>
    </header>

    <section class="appointment-section">
      <el-table
        :data="appointments"
        v-loading="loading"
        class="data-table"
        stripe
      >
        <el-table-column prop="patientId" label="患者ID" width="120" />
        <el-table-column prop="doctorId" label="医生ID" width="120" />
        <el-table-column label="预约时间" width="180">
          <template #default="{ row }">
            {{ new Date(row.appointmentTime).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="statusMap[row.status]?.color" effect="plain">
              {{ statusMap[row.status]?.text || row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 'PENDING'"
              type="primary"
              size="small"
              @click="confirmAppointment(row.id)"
            >
              确认预约
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </section>
  </div>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance, onMounted } from "vue";
const instance = getCurrentInstance();
const proxy = instance?.proxy as any;

import { useUserStore } from "@/stores/userStore";
const userStore = useUserStore();
const { token } = userStore.getUserData();
import { RequestParams } from "@/types/request";
import { PatientAppointmentItem } from "@/types/patient";

const appointments = ref<PatientAppointmentItem[]>([]);
const unconfirmedCount = ref<number>(0);
const loading = ref<boolean>(false);

//状态映射配置
const statusMap: any = {
  PENDING: { text: "待确认", color: "warning" },
  CONFIRMED: { text: "已确认", color: "success" },
  CANCELLED: { text: "已取消", color: "danger" },
};

//get appoint list
const fetchAppointments = async () => {
  try {
    loading.value = true;
    let result: any = await proxy.request({
      method: "get",
      url: proxy.api.manageAppointment,
      params: {} as RequestParams,
      headers: {
        authentication: token,
      },
    });
    if (!result) {
      return;
    }
    if (result.code === 1) {
      appointments.value = result.data;
      updateUnconfirmedCount();
    }
  } catch (error) {
    proxy.message.error("数据请求失败");
  } finally {
    loading.value = false;
  }
};

//update count
const updateUnconfirmedCount = () => {
  unconfirmedCount.value = appointments.value.filter(
    (item) => item.status === "PENDING"
  ).length;
};

//confirm appoint
const confirmAppointment = async (appointmentId: number) => {
  try {
    let result: any = await proxy.request({
      method: "get",
      url: proxy.api.manageConfirmAppointment,
      params: {
        id: appointmentId,
      } as RequestParams,
      headers: {
        authentication: token,
      },
    });
    if (!result) {
      return;
    }
    if (result.code === 1) {
      proxy.confirm({
        message: "确认该预约吗？",
        okfun: () => {
          appointments.value = appointments.value.filter(
            (item) => item.id !== appointmentId
          );
          updateUnconfirmedCount();
          fetchAppointments();
          proxy.message.success("预约确认成功");
        },
      });
    }
  } catch (error) {
    proxy.message.error("确认预约失败");
  }
};

//实时排队人数
const fetchUnconfirmedCount = async () => {
  let result: any = await proxy.request({
    method: "get",
    url: proxy.api.dataUnconfirmedCount,
    params: {} as RequestParams,
    headers: {
      authentication: token,
    },
  });
  if (!result) {
    return;
  }
  if (result.code === 1) {
    unconfirmedCount.value = result.data;
  }
};

onMounted(() => {
  fetchAppointments();
  fetchUnconfirmedCount();
});
</script>

<style scoped>
.management-container {
  padding: 24px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.header-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  position: relative;
  padding-left: 12px;
}

.title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 1.2em;
  background: #409eff;
  border-radius: 2px;
}

.stats-badge {
  display: flex;
  gap: 12px;
}

.data-table {
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #ebeef5;
}

.data-table :deep(.el-table__cell) {
  padding: 12px 0;
}

.action-group {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}
</style>
